// pages/Order/Orders/Orders.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getToken , codeLogin } from '../../../api/login';
import { queryUserWechatOpenId , getUserAccount , getUser } from '../../../api/user';
import { queryTravelOrderForm , payTravelOrderForm } from '../../../api/travel';
import { throttle } from '../../../utils/util';
import { ACCESS_TOKEN } from '../../../utils/types';
const regeneratorRuntime = require('../../../common/runtime');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    orderStatus: '',
    goodsName: '',
    tabList: [
      { id: '', name: '全部'},{ id: '1', name: '待出行'},{ id: '0', name: '待支付'},{ id: '3', name: '已取消'},{ id: '4', name: '已完成'},
    ],
    active: '',
    activeIndex: 0,
    page: 0,
    isReachBottom: false,
    noMore: false,
    loading: false,
    loadingFailed: false,
    dataList: [],
    showGoOnPay: false,
    balance: 0,
    openId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.orderStatus != 'null'){
      this.setData({
        active: options.orderStatus,
      })
    }
    let _this = this;
    if (wx.onNeedPrivacyAuthorization) {
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
      })
    }
    if(wx.getStorageSync(ACCESS_TOKEN) == null || wx.getStorageSync(ACCESS_TOKEN) == ''){
      this.login();
    }else{
      this._getOrders();
      this.allData();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._getOrders();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._getOrders()
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 获取所有接口
  allData(){
    this._getUserAccount('0');
    this._queryUserWechatUnionId();
  },
  // 登录
  login(){
    var expires_in = wx.getStorageSync('expires_in');
    console.log(expires_in,'expires_in');
    // 获取服务器token
    getToken().then(res => {
      let _this = this;
      if(res.success){
          wx.setStorageSync(ACCESS_TOKEN, res[ACCESS_TOKEN]);
          // 登录
          wx.login({
            success: logRes => {
              // 发送 res.code 到后台换取 openId, sessionKey, unionId
              console.log(logRes,'logRes')
              if (logRes.code) {
                codeLogin(logRes.code,_this.data.parentUserId)
                .then(rres => {
                  console.log(rres,'第一次登录返回的rres')
                  if(rres.success){
                      wx.setStorageSync(ACCESS_TOKEN, rres.access_token);
                      wx.setStorageSync('expires_in', rres.expires_in);
                      setTimeout(() => {
                        getUser({})
                        .then(user => {
                          if(user.success){
                            wx.setStorageSync('userId', user.data.userId)
                            wx.setStorageSync('phone', user.data.phone)
                            _this._getOrders();
                            _this.allData();
                          }
                        })
                      }, 500);
                  }
                })
              } else {
                wx.showToast({
                  title: logRes.errMsg,
                  icon: 'none',
                })
              }
            },
          })
      }else{
          wx.showToast({
              title: res.errMessage,
              icon: 'none'
          })
      }
    })
  },
  // 输入框发生变化
  onSearchChange(e) {
    this.setData({
      goodsName: e.detail,
    });
  },
  // 输入框搜索
  onSearch(){
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._getOrders();
  },
  // tab切换
  onChange(e){
    console.log(e)
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      active: e.detail.name,
    })
    this._getOrders();
  },
  // 查询订单数据
  _getOrders(){
    let _this = this;
    queryTravelOrderForm({status: _this.data.active,page: _this.data.page,})
    .then(async (res) => {
      if(res.success){
        var list = _this.data.dataList;
        let arr = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          console.log(item,'item')
          item.info = JSON.parse(item.item);
          if(item.itemType != 3){
            item.info.titleImgUrlList = item.info.titleImgUrl.split(',');
          }
          item.travelUser = JSON.parse(item.travelUser);
          arr.push(item);
        }
        if(_this.data.page == 0){
          list = arr;
        }else{
          list.concat(arr);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 取消订单
  cancelOrder(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.showModal({
      title: '温馨提示',
      content: '是否取消当前订单？',
      complete: (res) => {
        if (res.confirm) {
          cancelGroupMealGoodsOrderStatus({orderCode: item.orderCode})
          .then(res => {
            if(res.success){
              wx.showToast({
                title: '操作成功',
                icon: 'none'
              });
              _this.updateOrder({orderCode: item.orderCode});
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none',
              })
            }
          })
        }
      }
    })
  },
  // 替换订单数据
  async updateOrder({orderCode}){
    let _this = this;
    try {
      var order = await _this._queryOneOrder({orderCode: orderCode});
      var index = _this.data.dataList.findIndex(item => item.orderCode == orderCode);
      var list = _this.data.dataList;
      list[index] = order;
      _this.setData({
        dataList: list,
      })
    } catch (error) {
      wx.showToast({
        title: error,
        icon: 'none',
      })
    }
  },
  // 查询单个订单数据
  _queryOneOrder({orderCode}){
    return new Promise((resolve,reject) => {
      queryTravelOrderForm({orderCode: orderCode})
      .then(res => {
        if(res.success){
          if(res.data.content.length > 0){
            const item = res.data.content[index];
            console.log(item,'item')
            item.info = JSON.parse(item.item);
            if(item.itemType != 3){
              item.info.titleImgUrlList = item.info.titleImgUrl.split(',');
            }
            item.travelUser = JSON.parse(item.travelUser);
            resolve(item);
          }else{
            reject('暂未获取到订单数据');
          }
        }else{
          reject(res.errMessage);
        }
      })
    })
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              openId: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 获取用户账户余额
  _getUserAccount(type){
    let _this = this;
    getUserAccount(type)
    .then(res => {
      if(res.success){
        if(type == 0){
          _this.setData({
            balance : res.data.balance,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 去支付
  goPay(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    if(item.paidAmount > 0){
      // 如果之前是组合支付，那么继续支付就默认使用微信支付
      _this.pay({orderCode: item.orderCode,payType: 2,isMixPay: '1'});
    }else{
      _this.setData({
        showGoOnPay: true,
        payAmount: item.paymentPrice,
        payType: _this.data.balance < item.payAmount ? 2 : '0',
        goOnPayOrderCode: item.orderCode,
      })
    }
  },
  onClose(){
    this.setData({
      showGoOnPay: false,
    })
  },
  // 选择维信支付
  selWechatPay(e){
    let payType = e.target.dataset.type||e.currentTarget.dataset.type;
    this.setData({
      payType: payType,
    })
  },
  // 确认选择通道继续支付
  submitGoOnPay(){
    if(this.data.payType == '0'){
      if(this.data.payAmount > this.data.balance){
        // wx.showToast({
        //   title: '当前账户余额不足，请更换其他支付方式',
        //   icon: 'none',
        // })
        // return;
        wx.showModal({
          title: '温馨提示',
          content: '当前余额不足，是否前往充值？',
          success: (modal) =>{
            if(modal.confirm){
              wx.navigateTo({
                url: '/pages/Earnings/UpTopBalance/UpTopBalance',
                events: {
                  'updateUserAccount': function(){
                    this._getUserAccount('0');
                  },
                }
              })
            }
          },
        });
        return
      }
    }
    if(this.data.payType == '0'){
      const child = this.selectComponent('.pay-passwordAuth');
      child.clearPassword();
      child.openPayAuth();
    }else{
      this.pay({orderCode: this.data.goOnPayOrderCode,payType: this.data.payType});
    }
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    this.setData({
      payPassword: e.detail,
    })
    this.pay({orderCode: this.data.goOnPayOrderCode,payType: this.data.payType});
  },
  pay({orderCode,payType,isMixPay,}){
    let _this = this;
    payTravelOrderForm({payType: payType,orderCode: orderCode,openId: _this.data.openId,payPassword: _this.data.payType == '0' ? _this.data.payPassword : null}).then(res => {
      if(res.success){
        _this.wechatPay({payType: payType,wechatSign: res.data ? res.data.data : res.data});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 支付
  wechatPay({payType,wechatSign}){
    let _this = this;
    if(payType == '0'){
      _this.setData({
        page: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
        showGoOnPay: false,
      })
      _this._getUserAccount('0');
      _this._getOrders();
      wx.showToast({
        title: '支付成功',
        icon: 'success'
      })
    }else{
      console.log((wechatSign),'jsonData');
      var order = JSON.parse(wechatSign)
      // TODO微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp.toString(),
        nonceStr: order.nonceStr,
        package: order.package,
        signType: order.signType,
        paySign: order.paySign,
        success: () => {
          _this.setData({
            page: 0,
            isReachBottom: false,
            noMore: false,
            loading: false,
            loadingFailed: false,
            showGoOnPay: false,
          })
          _this._getOrders();
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.log(err,'err')
          wx.showToast({
            title: '取消支付',
            icon: 'none',
          })
        }
      })
    }
  },
  // 跳转详情
  goDetail(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/Order/OrderDetail/OrderDetail?orderCode=${item.orderCode}`,
      events: {
        'updateOrder': function(){
          _this.setData({
            page: 0,
            isReachBottom: false,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
          _this._getOrders();
        }
      }
    })
  },
})